package tool

import (
	"database/sql"
	"fmt"
	"github.com/go-redis/redis"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"strconv"
)

type Url struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	DataBase string `yaml:"database"`
}

func getUrl(url Url) string {
	urlStr := url.Username + ":" + url.Password + "@tcp(" + url.Host + ":" + strconv.Itoa(url.Port) + ")/" + url.DataBase + "?charset=utf8&parseTime=true"
	fmt.Println("url:", urlStr)
	return urlStr
}

func GetSqlConnection(url Url) *sql.DB {
	urlStr := getUrl(url)

	db, err := sql.Open("mysql", urlStr)
	if err != nil {
		err.Error()
	}

	return db
}

func GetGormConnection(url Url) *gorm.DB {
	urlStr := getUrl(url)
	db, err := gorm.Open(mysql.Open(urlStr), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		err.Error()
	}
	return db
}

func GetRedisConnection() *redis.Client {
	client := redis.NewClient(&redis.Options{
		Network:  "",
		Addr:     "124.221.212.162:6379",
		Password: "ylb305042026",
		DB:       3,
	})

	return client

}
